package server;

import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.*;
/**
 * Affiche les parametres du serveur
 * @author laurent Constantin
 * @version 1.0
 *
 */
public class JPanelServerSettings extends JPanel{

	private static final long serialVersionUID = 8039865630712074019L;
	
	private ServerApplication server;
    private JTextField inputPort = new JTextField();
    private JButton btnSetParams = new JButton();
	
    /**
     * Active ou desactive le boutton pour demarrer le serveur
     * et change son texte
     * @param canStart Indique si le bouton doit etre active ou non
     */
    public void allowStart(boolean canStart){
    	btnSetParams.setEnabled(canStart);
    	btnSetParams.setText((canStart?"Demarrer le serveur":"Le serveur a demarre"));
    	
    }
    /**
     * Demarre le serveur
     */
    public void startServer(){
		try {
			server.startServer(Integer.parseInt(inputPort.getText()));
			allowStart(false);
		} catch (Exception e) {
			JOptionPane.showMessageDialog(this,
					"Le port n'est pas valide", "Port invalide",
					JOptionPane.ERROR_MESSAGE);
			allowStart(true);
			return;
		}
    };
	/**
	 * Instancie le paneau
	 * @param server l'application serveur
	 */
	public JPanelServerSettings(ServerApplication server){
		
		
		this.server = server;
		
		JPanel haut = new JPanel();
	    haut.setLayout(new GridLayout(1,2));
	    
	    JPanel bas = new JPanel();
	    bas.setLayout(new GridLayout(1,2));
	    
	    setLayout(new BoxLayout(this,2));
	    
	    setPreferredSize(new Dimension(250,110));
        setSize(600,80);

        inputPort.setPreferredSize(new Dimension(100,20));
        inputPort.setText( server.getNoPort()+"" );

        btnSetParams.addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent e) {
                JPanelServerSettings.this.startServer();
            }
        });

        setLayout(new FlowLayout());

        add(new JLabel("Demarrer le serveur :"));
        bas.add(new JLabel("Port : "),LEFT_ALIGNMENT);
        bas.add(inputPort,RIGHT_ALIGNMENT);
        add(haut);
        add(bas);
        add(btnSetParams,RIGHT_ALIGNMENT);

        allowStart(true);
	}
	
	
}
